import { Component, OnInit, AfterViewInit } from '@angular/core';
import { SystemService } from 'app/service/system.service';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { AuthService } from './auth.service';
import { MessagesService } from 'app/shared/service';
import { Router } from '@angular/router';
import { sha256 } from 'js-sha256';
import { PublicService } from 'app/public/public.service';
@Component({
    selector: 'itmp-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit, AfterViewInit {
    loginForm: FormGroup;
    clickLoding = false;
    constructor(
        public systemService: SystemService,
        private fb: FormBuilder,
        private authService: AuthService,
        private msg: MessagesService,
        private router: Router,
        private pubSer: PublicService
    ) {
        // 语言服务
        this.systemService.langSet();
    }

    ngOnInit() {
        this.loginForm = this.fb.group({
            username: ['', Validators.required],
            password: ['', Validators.required],
            remember: ['']
        });
    }

    ngAfterViewInit(): void {
        setTimeout(() => this.systemService.timeSet());
    }
    // getRoleName(value, url) {
    //     const time = new Date().getTime();
    //     const param2 = {
    //         userName: value.username.toLowerCase(),
    //         token: sha256(value.username.toLowerCase() + value.password + time).toUpperCase(),
    //         time
    //     };
    //     this.authService.getRoleName(param2).subscribe(res => {
    //         if (res.code === '900002') {
    //             this.authService.getRoleNameLogOut(param2).subscribe(data => {
    //                 this.getRoleName(value, url);
    //             });
    //         } else {
    //             this._setStorage('roleName', res.data.userRole.roleName);
    //             this.router.navigate(url);
    //         }
    //     });
    // }
    login() {
        for (const i in this.loginForm.controls) {
            if (this.loginForm.controls.hasOwnProperty(i)) {
                this.loginForm.controls[i].markAsDirty();
                this.loginForm.controls[i].updateValueAndValidity();
            }
        }

        if (this.loginForm.invalid) {
            return;
        }

        this.clickLoding = true;
        const value = this.loginForm.value;
        // const param = {
        //     username: value.username.toLowerCase(),
        //     // password: value.password
        //     password: sha256(value.password)
        // };
        const param = new FormData();
        param.append('username', value.username.toLowerCase());
        param.append('password', sha256(value.password));
        this.authService.login(param).subscribe(
            res => {
                this.clickLoding = false;
                if (res['code'] === '000000') {
                    let userInfo;
                    try {
                        userInfo = res['data'];
                        this.msg.success(res['msg']);
                        this._setUserInfo(userInfo);
                        this.pubSer.syncEnumInfoToRedis().subscribe(response => {
                            this.pubSer.getSelectOptionsListFromBackend().subscribe(data => {
                                if (data.code === '000000') {
                                    this.pubSer.optionsList = data.data;
                                    this.systemService.showPage = true;
                                    this.router.navigate(['/ccm/data-visualization/overall']);
                                }
                            });
                        });
                        // this.getRoleName(value, ['/ccm/data-visualization/overall']);
                    } catch (e) {
                        this.msg.error('err user name or password');
                    }
                } else {
                    this.msg.error(res['msg']);
                }
            },
            err => {
                this.clickLoding = false;
                this.msg.error('err user name or password');
            }
        );
    }

    private _setStorage(key, value): void {
        localStorage.setItem(key, value);
    }

    private _setUserInfo(userInfo: any): void {
        this._setStorage('user_id', userInfo.userId);
        this._setStorage('access_token', userInfo.Authorization);
        this._setStorage('user_name', userInfo.name);
        this._setStorage('role_id', userInfo.roleId);
        this._setStorage('roleName', userInfo.roleName);
        this._setStorage('alertSwitch', true); // 设置alert的全局开关，用于alert的时候，地图是否展示
    }
}
